using B.S.XZYData.Api.Wrter.Application.Command.SalesOrder;
using B.S.XZYData.Domain.XZY;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using SalesOrderEntity = B.S.XZYData.Domain.XZY.SalesOrder;
using SalesOrderProductEntity = B.S.XZYData.Domain.XZY.SalesOrderProduct;

namespace B.S.XZYData.Api.Wrter.Application.Handler.SalesOrder
{
    /// <summary>
    /// 删除销售订单处理器
    /// </summary>
    public class DeleteSalesOrderHandler : IRequestHandler<DeleteSalesOrderCommand, ApiResult<string>>
    {
        private readonly IBaseRepository<SalesOrderEntity> _salesOrderRepo;
        private readonly IBaseRepository<SalesOrderProductEntity> _salesOrderProductRepo;

        public DeleteSalesOrderHandler(
            IBaseRepository<SalesOrderEntity> salesOrderRepo,
            IBaseRepository<SalesOrderProductEntity> salesOrderProductRepo)
        {
            _salesOrderRepo = salesOrderRepo;
            _salesOrderProductRepo = salesOrderProductRepo;
        }

        public async Task<ApiResult<string>> Handle(DeleteSalesOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (request.Ids == null || !request.Ids.Any())
                {
                    return ApiResult<string>.Error("请选择要删除的销售订单");
                }

                var successCount = 0;
                var failCount = 0;
                var errorMessages = new List<string>();

                foreach (var id in request.Ids)
                {
                    try
                    {
                        // 检查销售订单是否存在
                        var existingOrder = await _salesOrderRepo.GetValue(id);
                        if (existingOrder == null)
                        {
                            failCount++;
                            errorMessages.Add($"销售订单ID {id} 不存在");
                            continue;
                        }

                        // 逻辑删除销售订单
                        existingOrder.IsDeleted = true;
                        existingOrder.ModifyTime = DateTime.Now;
                        existingOrder.ModifierId = 1; // 这里应该从当前用户上下文获取

                        await _salesOrderRepo.UpdateAsync(existingOrder);

                        // 逻辑删除相关的产品明细
                        var existingProducts = await _salesOrderProductRepo.GetAllAsync(x => 
                            x.SalesOrderId == id);
                        
                        foreach (var product in existingProducts)
                        {
                            product.IsDeleted = true;
                            product.ModifyTime = DateTime.Now;
                            product.ModifierId = 1; // 这里应该从当前用户上下文获取
                            await _salesOrderProductRepo.UpdateAsync(product);
                        }

                        successCount++;
                    }
                    catch (Exception ex)
                    {
                        failCount++;
                        errorMessages.Add($"删除销售订单ID {id} 失败: {ex.Message}");
                    }
                }

                if (failCount == 0)
                {
                    return ApiResult<string>.Success($"成功删除 {successCount} 个销售订单");
                }
                else if (successCount == 0)
                {
                    return ApiResult<string>.Error($"删除失败: {string.Join("; ", errorMessages)}");
                }
                else
                {
                    return ApiResult<string>.Success($"部分删除成功: 成功 {successCount} 个，失败 {failCount} 个。失败原因: {string.Join("; ", errorMessages)}");
                }
            }
            catch (Exception ex)
            {
                return ApiResult<string>.Error($"删除销售订单失败：{ex.Message}");
            }
        }
    }
}
